package cn.tedu;

import java.sql.*;
import java.util.Scanner;

/**
 * select count(*) from user where username='tom' and password='123456';
 * count(*) 只能=1或=0
 */
public class Demo10 {
    //登录:输入用户名,密码
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = sc.nextLine();
        System.out.println("请输入密码:");
        String password = sc.nextLine();
        try(Connection conn = DBUtils.getConn()) {
            //Statement s = conn.createStatement();
            //?为占位符
            String sql = "select count(*) from user where username= ? and password= ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            //代码中1和2代表的是?的位置,到时会将变量把?替换
            //sql代码逻辑已经编译,提前锁死,现在用户输入的的内容则不会影响原有的sql语句的逻辑
            ps.setString(1,username);
            ps.setString(2,password);
            //System.out.println(sql);
            ResultSet rs = ps.executeQuery();
            rs.next();
            int count = rs.getInt(1);
            if(count >0) {
                System.out.println("登录成功");
            } else {
                System.out.println("用户名或密码错误");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
